package com.shiro.realms;

import org.apache.shiro.authc.*;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.util.ByteSource;

public class SecondRealm extends AuthenticatingRealm {

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("==================================================SecondRealm+++++++++++++++++++++++++++++++++++++++");
        System.out.println("doGetAuthenticationInfo: " + authenticationToken + "=============================================");
        //1、把AuthenticationToken转换为UsernamePasswordToke
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        //2、从UsernamePasswordToken中获取username
        String username = usernamePasswordToken.getUsername();
        //3、调用数据的方法，查询username的记录
        System.out.println("++++++++++++++++从数据库获取username: " + username + "所对应的信息");
        //4、若用户不存在，则可以抛出UnknowAccountException
        if ("unknow".equals(username)) {
            throw new UnknownAccountException("==========================================用户不存在==========================================");
        }
        //5、根据用户信息的情况，决定是否需要抛出其他的AuthenticationException
        if ("monster".equals(username)) {
            throw new LockedAccountException("==========================================用户被锁定==========================================");
        }
        //6、根据用户的情况，来构建AuthenticationInfo对象并返回，通常使用的实现类为SimpleAuthenticationInfo
        //以下信息是从数据库中获取的

        //principal:认证的实体信息，可以是username，也可以是数据库表对应的用户的实体类对象
        Object principal = username;
        //credentials 密码
        Object credentials = "";
        if ("admin".equals(username)){
            credentials = "ce2f6417c7e1d32c1d81a797ee0b499f87c5de06";
        }else if ("user".equals(username)){
            credentials = "073d4c3ae812935f23cb3f2a71943f49e082a718";
        }
        //realmName 当前realm对的name，调用父类的getName()方法即可
        String realmName = getName();
        // 盐值
        ByteSource credentialSalt = ByteSource.Util.bytes(username);
//        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal,credentials,realmName);
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal, credentials, credentialSalt, realmName);

        return info;
    }
}
